<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Hash;
use DB;
class UserController extends Controller
{
   public function getAdd(){
    return view('admin.user.add');
   }


   // 添加
   public function postInsert(Request $request){
        //自动表单验证
        $this -> validate($request,[
            'username' => 'required',
            'password' => 'required',
            'repassword' => 'required|same:password',
            'email' => 'email',
            'sex' => 'required'
            ],[
            'username.required' => '请填写用户名',
            'password.required' => '请填写密码',
            'repassword.required' => '确认密码不存在',
            'repassword.same' => '确认密码不一致',
            'email.email' => '邮箱格式不正确',
            'sex.required' => '请选择性别'
            ]);

       // 数据组装
       $arr = $request -> only(['username','email','sex']);
       // 将密码使用哈希加密
       $arr['password'] = Hash::make($request -> input('password'));
       // 随机token 值的长度
       $arr['token'] = str_random(50);
       // 获取创建时间
       $arr['createTime'] = date('Y-m-d H:i:s',time());
       // 插入到数据库
       $res = DB::table('shop_users') -> insert($arr);
       // 判断数据是否合法
       if($res){
        return redirect('/admin/user/index') -> with('success','添加成功');
       }else{
        return back() -> with('error','添加失败');
       }
   }

   // 搜索分页
   public function getIndex(Request $request){
        // 接收表单传值
        $count = $request -> input('count','10');
        // 搜索相似值
        $search = $request -> input('search','');
        //  paginate 查询数据   并且分页         
        $data = DB::table('shop_users') -> where('username','like','%'.$search.'%') -> paginate($count);
        return view('admin/user/index',['data'=>$data,'request'=>$request->all()]);
   }

   // 删除操作
   public function getDelete($id){
        // 准备sql语句
    $res = DB::table('shop_users') -> where('h_uid',$id) -> delete();
   //进行判断
    if($res){
        return redirect('/admin/user/index')->with('success','删除成功');
    }else{
        return back()->with('error','删除失败');
    }
   }


   // 用户修改解析模板
  public function getEdit($id){
    $data = DB::table('shop_users') -> where('h_uid',$id) -> first();
    return view('admin.user.edit',['data'=>$data]);
   }


   // 用户修改
   public function postUpdate(Request $request){
    // 获取数据
    $arr = $request -> except(['_token','h_uid']);

    // 进行修改
    $res = DB::table('shop_users') -> where('h_uid',$request->input('h_uid')) ->update($arr);

    // 进行判断
    if($res){
        return redirect('/admin/user/index')->with('success','修改成功');
    }else{
        return back()->with('error','修改失败');
    }
   }
}
